package com.hanlink.dsp.ui.fragment;

import android.content.Context;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelProviders;

import com.edge.pbxdsp.R;
import com.hanlink.dsp.BtDspApplication;

import com.hanlink.dsp.bluetooth.ble.BtDevice;
import com.hanlink.dsp.protocols.DeviceProtocol;
import com.hanlink.dsp.ui.CaAmpDspActivity;
import com.hanlink.dsp.ui.activities.DViewModel;
import com.hanlink.dsp.ui.adapter.DeviceAdapter;
import com.hanlink.dsp.util.DialogHelper;
import com.hanlink.dsp.util.YzToast;
import com.inuker.bluetooth.library.Constants;
import com.inuker.bluetooth.library.search.SearchResult;
import com.qztech.bluetooth.BluetoothClientManager;
import com.qztech.bluetooth.BluetoothConfig;
import com.qztech.bluetooth.ZBtDevice;
import com.qztech.bluetooth.event.BleConnectStatusEvent;
import com.qztech.bluetooth.event.DeviceFoundedEvent;
import com.qztech.bluetooth.event.SearchStateEvent;
import com.qztech.sdk.ui.fragment.BaseFragment;
import com.qztech.utils.YzDebug;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

//import butterknife.BindView;
//import butterknife.ButterKnife;
//import butterknife.OnClick;

@SuppressWarnings("unused")
public class DeviceDialogFragment extends BaseFragment {
    private DeviceAdapter mAdapter;

    //@BindView(R.id.btn_refresh)
    public Button mBtnRefresh;
    //@BindView(R.id.src_source)
    public Button mBtnSrcSource;
    //@BindView(R.id.src_bluetooth)
    public Button mBtnSrcBluetooth;
    private List<BtDevice> mFoundDevice = new ArrayList<>();
    //@BindView(R.id.lvItems)
    public ListView mListDevices;
    //@BindView(R.id.pgbLoading)
    public ProgressBar mLoadingBar;

    //@BindView(R.id.radioGroup)
    RadioGroup mTypeGroup;

    private DViewModel mHomeViewModel;
    private int mClickCount;
    private long mLastClickTimeTs;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        EventBus.getDefault().register(this);
        mHomeViewModel = ViewModelProviders.of(getActivity(), new ViewModelProvider.AndroidViewModelFactory(getActivity().getApplication())).get(DViewModel.class);
    }




    private void initViews(){
        mBtnRefresh = findViewById(R.id.btn_refresh);
        mBtnSrcSource = findViewById(R.id.src_source);
        mBtnSrcBluetooth = findViewById(R.id.src_bluetooth);
        mListDevices = findViewById(R.id.lvItems);
        mLoadingBar = findViewById(R.id.pgbLoading);
        mTypeGroup  = findViewById(R.id.radioGroup);


        findViewById(R.id.btnResetApp).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getActivity() instanceof CaAmpDspActivity) {
                    ((CaAmpDspActivity) Objects.requireNonNull(getActivity())).resetAppAsk();
                }
            }
        });

        mBtnRefresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                refreshList();
            }
        });
        mBtnSrcSource.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setSrcState(true);
            }
        });
        mBtnSrcBluetooth.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setSrcState(false);
            }
        });

    }

    @Override
    public void onDestroy() {
        YzDebug.d("++++++++++++++++++++++++++++++++++++++++++++++");
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    protected int getResourceId() {
        return R.layout.fragment_drawer_bluetooth;

    }

    public void onDestroyView() {

        mHomeViewModel.cancelSearch();
        super.onDestroyView();
    }

    public void onPause() {
        super.onPause();
        mHomeViewModel.cancelSearch();
    }

    public void onRefreshFragment(int paramInt) {
    }

    public void onResume() {
        super.onResume();
        addConnectedDevice();
    }

    public void onViewCreated(@NonNull View paramView, Bundle paramBundle) {
        super.onViewCreated(paramView, paramBundle);
       // ButterKnife.bind(this, paramView);
        initViews();
        this.mBtnRefresh.setVisibility(View.VISIBLE);
        this.mFoundDevice.clear();
        for (SearchResult result : BluetoothClientManager.getInstance(getContext()).getFoundDeviceList()) {
            mFoundDevice.add(new BtDevice(result.getAddress(), result.getName()));
        }
        addConnectedDevice();
//        mFoundDevice.add(new BtDevice("12345667890", "Testttt"));
//        mFoundDevice.add(new BtDevice("12345667891", "Testttt2"));
        this.mAdapter = new DeviceAdapter(getActivity(), this.mFoundDevice);
        this.mListDevices.setAdapter(this.mAdapter);
        this.mAdapter.setOnSwichChangedListener((isChecked, btDevice) -> {
            if (isChecked && !btDevice.isConnected()) {
                if (getActivity() instanceof CaAmpDspActivity) {
                    ((CaAmpDspActivity) getActivity()).connect(btDevice.getMac(), btDevice.getName());
                }
                return;
            }
            DialogHelper.confirm(DeviceDialogFragment.this.getActivity(), com.hanlink.res.R.string.title_device_confirm, com.hanlink.res.R.string.device_message_disconnect, com.hanlink.res.R.string.ok, com.hanlink.res.R.string.cancel, (paramAnonymous2DialogInterface, paramAnonymous2Int) -> {
                mHomeViewModel.disconnect();
                CaAmpDspActivity activity = (CaAmpDspActivity)getActivity();
                activity.getHomeViewModel().sageLastConnectDevice(null);
                activity.getCurrentFragment().updateByConnected(false);
                btDevice.setConnected(false);
                DeviceDialogFragment.this.mAdapter.notifyDataSetChanged();
            });
        });
        mTypeGroup.setOnCheckedChangeListener((group, checkedId) -> {
            if (checkedId == R.id.rb_source) {
                BluetoothClientManager.getInstance(BtDspApplication.getInstance()).write(DeviceProtocol.setMode(true));
            } else if (checkedId == R.id.rb_bluetooth) {
                BluetoothClientManager.getInstance(BtDspApplication.getInstance()).write(DeviceProtocol.setMode(false));
            }
        });
        if (mISrcState != -1){
            setSrcState(mISrcState == 1);
        }
    }

//    @OnClick({R.id.btn_refresh, R.id.btnResetApp ,R.id.src_bluetooth,R.id.src_source})
//    public void onBtnClick(View view) {
//        switch (view.getId()){
//            case R.id.btn_refresh:
//                refreshList();
//                break;
//            case R.id.btnResetApp:
//                if (getActivity() instanceof CaAmpDspActivity) {
//                    ((CaAmpDspActivity) Objects.requireNonNull(getActivity())).resetAppAsk();
//                }
//                break;
//            case R.id.src_source:
//                setSrcState(true);
//               break;
//            case R.id.src_bluetooth:
//                setSrcState(false);
//                break;
//        }
//    }

    private static int mISrcState = -1;
    private void updateUiBySrcState(){
        if (mISrcState == -1){
            mBtnSrcSource.setSelected(false);
            mBtnSrcBluetooth.setSelected(false);
        }else{
            mBtnSrcSource.setSelected(mISrcState == 1);
            mBtnSrcBluetooth.setSelected(mISrcState != 1);
        }
    }
    private void setSrcState(boolean isSource){
        if (BluetoothClientManager.getInstance(BtDspApplication.getInstance()).isConnect()){
            mISrcState = isSource?1:0;
            BluetoothClientManager.getInstance(BtDspApplication.getInstance()).write(DeviceProtocol.setMode(isSource));
        }else{
            YzToast.showShort(com.hanlink.res.R.string.bluetooth_error);
            mISrcState = -1;
        }
        updateUiBySrcState();

    }
    private void addConnectedDevice() {
        ZBtDevice localBleDevice = mHomeViewModel.getConnectedDevice();
        if (localBleDevice != null) {
            BtDevice btDevice = new BtDevice();
            btDevice.setConnected(true);
            btDevice.setMac(localBleDevice.getMac());
            btDevice.setName(localBleDevice.getName());
            mFoundDevice.remove(btDevice);
            mFoundDevice.add(btDevice);
//            if (!mFoundDevice.contains(btDevice)) {
//                mFoundDevice.add(btDevice);
//            }
        }
    }

    public void refreshList() {
        this.mFoundDevice.clear();
        addConnectedDevice();
        if (BluetoothClientManager.getInstance(getContext()).isBluetoothOpened()) {
           // YzToast.showShort("刷新列表  开始");
            mHomeViewModel.searchBluetooth();
        } else{
          //  YzToast.showShort("刷新列表  蓝牙没有打开");
            BluetoothClientManager.getInstance(getContext()).openBluetooth();
        }
    }



    //-----BluetoothEvent---------------

    /**
     * 发现设备
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onFoundDevice(DeviceFoundedEvent event) {
        SearchResult searchResult = event.getDevice();
        if (!BluetoothConfig.isAvailableName(searchResult.getName())) return;
        for (BtDevice btDevice : mFoundDevice) {
            if ((btDevice).getMac().equalsIgnoreCase(searchResult.getAddress())) {
                return;
            }
        }
        BtDevice btDevice = new BtDevice(searchResult.getAddress(), searchResult.getName());
        if (mFoundDevice.contains(btDevice)) return;
        mFoundDevice.add(btDevice);
        mAdapter.notifyDataSetChanged();

    }

    /**
     * 搜索事件
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSearchEvent(SearchStateEvent event) {
        switch (event.getStatus()) {
            case SearchStateEvent.SEARCH_START:
                mLoadingBar.setVisibility(View.VISIBLE);
                mBtnRefresh.setEnabled(false);
                break;
            case SearchStateEvent.SEARCH_STOP:
            case SearchStateEvent.SEARCH_CANCEL:
                mLoadingBar.setVisibility(View.GONE);
                mBtnRefresh.setEnabled(true);
                break;
        }
    }

    /**
     * 蓝牙设备连接状态变化
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onBluetoothStateChanged(BleConnectStatusEvent event) {
        switch (event.getStatus()) {
            case Constants.STATUS_DISCONNECTED:
                for (BtDevice device : mFoundDevice) {
                    if (device.getMac().equalsIgnoreCase(event.getDevice().getMac())) {
                        device.setConnected(false);
                        mAdapter.notifyDataSetChanged();
                        break;
                    }
                }
                break;
            case Constants.STATUS_CONNECTED:
                for (BtDevice device : mFoundDevice) {
                        if (device.getMac().equalsIgnoreCase(event.getDevice().getMac())) {
                            device.setConnected(true);
                            mAdapter.notifyDataSetChanged();
                            break;
                        }
                }
                break;
        }
    }
}
